package com.travel.utils;

import cn.hutool.crypto.digest.MD5;
import com.travel.exception.BusinessException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Base64;
import java.util.UUID;


@Slf4j

@Component
public class Base64ToImg {

    @Value("${img.save-path}")
    private String savePath;

    @Value("${img.base-url}")
    private String baseUrl;



//    @Autowired
//    private ImgProperties imgProperties;

    public String base64ToImgHerf(String base64){
        log.info("保存路径: {}", savePath);
        log.info("基础URL: {}", baseUrl);

        if(base64 == null || !base64.contains(",")) {
            throw new BusinessException("无效的Base64图片数据");
        }

        base64 = base64.substring(base64.indexOf(",", 1) + 1);
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] imgBytes = decoder.decode(base64);
        
        File dir = new File("src/main/resources/static/images");
        if (!dir.exists()) {
            dir.mkdirs();
        }
        
        String fileName = MD5.create().digestHex(UUID.randomUUID().toString());
        String filePath = "src/main/resources/static/images/" + fileName + ".png";
        String href_url = "http://localhost:8000/images/" + fileName + ".png";
        
        try(OutputStream out = new FileOutputStream(filePath)){
            out.write(imgBytes);
            out.flush();
            log.info("图片保存成功: {}", filePath);
        }catch (IOException e){
            log.error("图片保存失败: {}", e.getMessage());
            throw new BusinessException("图片保存失败: " + e.getMessage());
        }

        return href_url;
    }


}
